import { HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { PaginationList } from '../model/message';
import { RequestService } from './request.service';


export abstract class CommonApi<T> {
  protected baseUrl: string;
  protected baseRequest: RequestService;
  constructor(baseRequest: RequestService, baseUrl: string) {
    this.baseRequest = baseRequest;
    this.baseUrl = baseUrl;
  }

  public create(data: T): Observable<any> {
    const url = this.baseUrl + '/create';
    return this.baseRequest.post(url, data);
  }

  public delete(ids: Array<number>): Observable<any> {
    const url = this.baseUrl + '/delete';
    const data = new HttpParams({ fromObject: { ids: ids.toString() } });
    return this.baseRequest.post(url, data);
  }

  public list(params: HttpParams): Observable<PaginationList<T>> {
    const url = this.baseUrl + '/list';
    return this.baseRequest.get(url, params);
  }

  public update(id: number, data: T): Observable<any> {
    const url = this.baseUrl + '/update/' + id;
    return this.baseRequest.post(url, data);
  }

  public fetchItem(id: number): Observable<T> {
    const url = this.baseUrl + '/' + id;
    return this.baseRequest.get(url);
  }

  // TODO:测试用，应改为 baseUrl + listAll
  public listAll(): Observable<Array<T>> {
    const params = new HttpParams({
      fromObject: {
        pageNum: '1',
        pageSize: '100'
      }
    });
    return this.list(params).pipe(
      map(item => item.list),
    );
  }

}
